<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body style="height: 2000px;">
    
</body>
<script>
    function fn(){
    console.log("触发了");
}
document.onscroll=throttle(fn,1000);

//防抖
function debounce(fn,wait){
   let timer,result;
   const later=(context,args)=>setTimeout(()=>{
       timer=null;
       result=fn.apply(context,args)
       context=args=null;
   },wait)
   let debounced=function(...params){
        if(!timer){
            timer=later(this,params)
        }else{
            clearTimeout(timer);
            timer=later(this,params)
        }
   }
   debounced.cancel=function(){
       clearTimeout(timer);
       timer=null;
   }
   return debounced;
}
//节流
function throttle(fn,wait){
    let _lastTime=null;
    let throttled=function(...params){
        let _nowTime=new Date();
        if(_nowTime-_lastTime>wait||!_lastTime){
            fn();
            _lastTime=_nowTime;
        }
    }
    return throttled;
}
</script>
</html>